/***************************************************************************************
 * Copyright (c) 2014-2022 Zihao Yu, Nanjing University
 *
 * NEMU is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *
 * See the Mulan PSL v2 for more details.
 ***************************************************************************************/

#include <isa.h>
#include <cpu/cpu.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <memory/paddr.h>
#include "sdb.h"

static int is_batch_mode = false;

void init_regex();
void init_wp_pool();
void isa_reg_display();
void wp_display();
struct WP *new_wp(char *expr);
void free_wp(int no);
word_t expr(char *e, bool *success);
/* We use the `readline' library to provide more flexibility to read from stdin. */
static char *rl_gets()
{
  static char *line_read = NULL;

  if (line_read)
  {
    free(line_read);
    line_read = NULL;
  }

  line_read = readline("(nemu) ");

  if (line_read && *line_read)
  {
    add_history(line_read);
  }

  return line_read;
}

static int cmd_c(char *args)
{
  cpu_exec(-1);
  return 0;
}

static int cmd_q(char *args)
{
  return -1;
}
static int cmd_si(char *args)
{
  uint32_t n = 1; // n defaults to 1

  if (args)
  {
    /*parse args to N */
    char *arg = strtok(args, " ");
    bool success;
    n=expr(arg,&success);
    if(unlikely(!success)){
      P_ERROR("Num error, non-convertible part: %s", arg);
      return 0;
    }
  }
  cpu_exec(n);
  return 0;
}

static struct
{
  const char *subcmd;
  void (*handler)();
} info_cmd_table[] = {
    {"r", isa_reg_display},
    {"w", wp_display}};
#define INFO_NR_CMD ARRLEN(info_cmd_table)

static int cmd_info(char *args)
{
  char *arg = strtok(args, " ");
  if (arg)
  {
    int i;
    for (i = 0; i < INFO_NR_CMD; i++)
    {
      if (strcmp(arg, info_cmd_table[i].subcmd) == 0)
      {
        info_cmd_table[i].handler();
        return 0;
      }
    }
    if (i == INFO_NR_CMD)
    {
      P_ERROR("Unknown arg");
    }
  }
  else
  {
    P_ERROR("Please complete subsequent arg");
  }
  return 0;
}
#define GET_NEXT_TOKEN_FAILED 0
#define GET_NEXT_TOKEN_SUCCESS 1
#define GET_NEXT_TOKEN_END 2
static char *get_next_tok(char **str, int *status)
{
  char *str_end = *str + strlen(*str);
  char *token = strtok(*str, " ");
  *str = token + strlen(token) + 1;
  if (*str >= str_end + 1)
    *status = GET_NEXT_TOKEN_END;
  else
    *status = GET_NEXT_TOKEN_SUCCESS;
  return token;
}

static int cmd_x(char *args)
{
  int st;
  char *arg = get_next_tok(&args, &st);
  if (arg)
  {
    uint32_t n;
    bool success;
    n=expr(arg,&success);
    if(unlikely(!success)){
      P_ERROR("Num error, non-convertible part: %s", arg);
      return 0;
    }
    if (st != GET_NEXT_TOKEN_END)
    {
      arg = get_next_tok(&args, &st);
      uint32_t addr = expr(arg, &success);
      if (likely(success)){
        if(likely(n>=0)){
          for (int32_t i = 0; i < n; i++)
          printf("0x%08x\n", paddr_read(addr + i * (4 / sizeof(uint8_t)), 4));
        }
        else{
          for (int32_t i = n; i != 0; i++)
          printf("0x%08x\n", paddr_read(addr + i * (4 / sizeof(uint8_t)), 4));
        }
      }
      else{
        P_ERROR("Bad experssion");
      }
    }
    else
    {
      P_ERROR("Please complete subsequent arg");
    }
  }
  else
    P_ERROR("Please complete subsequent arg");
  return 0;
}

static int cmd_p(char *args)
{
  bool success;
  if(args==NULL)
    return 0;
  uint32_t x = expr(args, &success);
  if (success)
    printf("0x%08x\n", x);
  else
    P_ERROR("Bad experssion");
  return 0;
}
static int cmd_w(char *args)
{
  struct WP *p = new_wp(args);
  if (p)
    printf("Set watchpoint successfully\n");
  else
    P_ERROR("Bad watchpoint");
  return 0;
}
static int cmd_d(char *args)
{
  bool success;
  int x = expr(args, &success);
  if (success) free_wp(x);
  else P_ERROR("BAD NUM")
  return 0;
}
static int cmd_help(char *args);

static struct
{
  const char *name;
  const char *description;
  int (*handler)(char *);
} cmd_table[] = {
    {"help", "Display information about all supported commands", cmd_help},
    {"c", "Continue the execution of the program", cmd_c},
    {"q", "Exit NEMU", cmd_q},
    {"si", "Execute N instructions in one step and pause. N defaults to 1", cmd_si},
    {"info", "Display the state of reg or the state of watchpoint", cmd_info},
    {"x", "Output N values started at memory address by hexadecimal", cmd_x},
    {"p", "Calculate the value of the expression", cmd_p},
    {"w", "Set the watchpoint", cmd_w},
    {"d", "Delete the watchpoint with serial number N", cmd_d},
    /* TODO: Add more commands */

};

#define NR_CMD ARRLEN(cmd_table)

static int cmd_help(char *args)
{
  /* extract the first argument */
  char *arg = strtok(args, " ");
  int i;

  if (arg == NULL)
  {
    /* no argument given */
    for (i = 0; i < NR_CMD; i++)
    {
      printf("%s - %s\n", cmd_table[i].name, cmd_table[i].description);
    }
  }
  else
  {
    for (i = 0; i < NR_CMD; i++)
    {
      if (strcmp(arg, cmd_table[i].name) == 0)
      {
        printf("%s - %s\n", cmd_table[i].name, cmd_table[i].description);
        return 0;
      }
    }
    printf("Unknown command '%s'\n", arg);
  }
  return 0;
}

void sdb_set_batch_mode()
{
  is_batch_mode = true;
}

void sdb_mainloop()
{
  if (is_batch_mode)
  {
    cmd_c(NULL);
    return;
  }

  for (char *str; (str = rl_gets()) != NULL;)
  {
    char *str_end = str + strlen(str);

    /* extract the first token as the command */
    char *cmd = strtok(str, " ");
    if (cmd == NULL)
    {
      continue;
    }

    /* treat the remaining string as the arguments,
     * which may need further parsing
     */
    char *args = cmd + strlen(cmd) + 1;
    if (args >= str_end)
    {
      args = NULL;
    }

#ifdef CONFIG_DEVICE
    extern void sdl_clear_event_queue();
    sdl_clear_event_queue();
#endif

    int i;
    for (i = 0; i < NR_CMD; i++)
    {
      if (strcmp(cmd, cmd_table[i].name) == 0)
      {
        if (cmd_table[i].handler(args) < 0)
          return;
        break;
      }
    }

    if (i == NR_CMD)
    {
      printf("Unknown command '%s'\n", cmd);
    }
  }
}

void init_sdb()
{
  /* Compile the regular expressions. */
  init_regex();

  /* Initialize the watchpoint pool. */
  init_wp_pool();
}
